package com.byedu.parser;

import com.byedu.model.constants.APIConstants;
import com.byedu.model.constants.SubOptionType;
import com.byedu.domain.course.AnswerDO;
import com.byedu.domain.course.LibraryDO;
import com.byedu.domain.course.QuestionDO;
import com.byedu.model.enums.QuestionTypeEnum;
import com.byedu.model.exception.ApiException;
import com.byedu.util.CommonDateUtil;
import com.byedu.util.ExcelUtil;
import com.byedu.util.IDGeneratorUtil;
import com.byedu.util.QuestionUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.*;

/**
 * Created by jason on 2017/6/4.
 */
public class LibraryExcelParser extends AbstractFileParser {

    private static final Logger logger = LoggerFactory.getLogger(LibraryExcelParser.class);

    public LibraryExcelParser() {
    }

    @Override
    public Map<String, Object> parseFile(File file,LibraryDO libraryDO) throws ApiException {

        Workbook workbook = ExcelUtil.createXSSFWorkbook(file);
        if (workbook == null) {
            workbook = ExcelUtil.createHSSFWorkbook(file);
            if(workbook==null) {
                logger.error(file.getName()+"请上传xls或者xlsx格式的文件！");
                throw new ApiException(file.getName()+"\n请上传xls或者xlsx格式的文件！");
            }
        }

        Sheet sheet = workbook.getSheetAt(0);

        if (sheet == null) {
            logger.error(file.getName()+"获取Excel表Sheet错误！");
            throw new ApiException(file.getName()+"\n获取Excel表Sheet错误！！");
        }

        if (sheet.getPhysicalNumberOfRows() <= 1) {
            logger.error(file.getName()+"文件内容为空！");
            throw new ApiException(file.getName()+"\n文件内容为空！");
        }

        //解析数据
        Map<String, Object> map = new HashMap<String, Object>();
        List<AnswerDO> answerDOList = new ArrayList<AnswerDO>();
        List<QuestionDO> questionDOList = new ArrayList<QuestionDO>();


        boolean isRight = true;
        String sbString = "";

        for (int i = 1; i <= sheet.getPhysicalNumberOfRows(); i++) {
            String uniqueKey = null;
            uniqueKey = IDGeneratorUtil.generateKey(new Date(), CommonDateUtil.YYYYMMDDHHMMSSSSS, String.valueOf(i), 6);
            int columnCount = 0;
            QuestionDO questionDO = new QuestionDO();
            questionDO.setLibraryId(libraryDO.getId());
            questionDO.setUniqueKey(uniqueKey);
            questionDO.setCtype(QuestionUtil.getQuestionTypeName(file.getName()));

            Row row = sheet.getRow(i);
            int columnSize = 8;
            if( QuestionTypeEnum.judgments.name().equals(questionDO.getCtype())){
                columnSize= 4;
            }
            if( QuestionTypeEnum.multiple.name().equals(questionDO.getCtype())){
                columnSize= 9;
            }

            if (row == null) {
                continue;
            }
            //序号
            String serialno = ExcelUtil.getCellValue(row.getCell(0));
            if (StringUtils.isNotEmpty(serialno)) {
                try {
                    Integer no = Integer.parseInt(serialno);
                    questionDO.setNo(no);
                }catch (Exception e){
                    isRight=false;
                    sbString=sbString+"第"+(i+1)+"行获取的序号错误！</br>";
                }
            } else {
                isRight=false;
                sbString=sbString+"第"+(i+1)+"行获取的序号错误！</br>";
            }
            columnCount++;
            //第二列是题目，
            String content = ExcelUtil.getCellValue(row.getCell(1));
            if (StringUtils.isNotEmpty(content)) {
                questionDO.setContent(content);
            } else {
                isRight=false;
                sbString=sbString+"第"+(i+1)+"行获取的题目错误！</br>";

            }
            columnCount++;
            //倒数第一列是解析
            String analysis = ExcelUtil.getCellValue(row.getCell(columnSize - 1));
            if (StringUtils.isNotEmpty(analysis)) {
                questionDO.setAnalysis(analysis);
            } else {
                isRight=false;
//                throw new Exception(file.getName()+"第"+(i+1)+"行获取解析错误！");
                sbString=sbString+"第"+(i+1)+"行获取的解析错误！</br>";
            }
            columnCount++;
            // 倒数第二列是正确答案，其中判断题只有正确答案，
            String correctAnswerStr = ExcelUtil.getCellValue(row.getCell(columnSize - 2));
            if (StringUtils.isNotEmpty(correctAnswerStr)) {
                columnCount++;
                if (columnCount == columnSize) {//判断题
                    if(SubOptionType.RIGHT.getValue().equals(correctAnswerStr)) {
                        AnswerDO right = new AnswerDO(correctAnswerStr, "", uniqueKey);
                        right.setCorrect(true);
                        answerDOList.add(right);

                        AnswerDO wrong = new AnswerDO(SubOptionType.WRONG.getValue(), "", uniqueKey);
                        answerDOList.add(wrong);
                    } else {
                        AnswerDO right = new AnswerDO(SubOptionType.RIGHT.getValue(), "", uniqueKey);
                        answerDOList.add(right);

                        AnswerDO wrong = new AnswerDO(correctAnswerStr, "", uniqueKey);
                        wrong.setCorrect(true);
                        answerDOList.add(wrong);
                    }
                } else {//选择题
                    //获取考题选项信息
                    int answersColumnSize = columnSize - columnCount;
                    for (int code = 0; code < answersColumnSize; code++) {
                        String answerContext = ExcelUtil.getCellValue(row.getCell(code + 2));

                        if (StringUtils.isNotEmpty(answerContext)) {
                            String subOption = SubOptionType.getValue(code);
                            AnswerDO answerDO = new AnswerDO(subOption, answerContext, uniqueKey);
                            if (correctAnswerStr.indexOf(subOption) != -1) {
                                answerDO.setCorrect(true);
                            }
                            answerDOList.add(answerDO);
                        }else{
                            isRight=false;
                            sbString=sbString+"第"+(i+1)+"行获取的答案错误！</br>";

                        }
                    }
                }
            } else {
                isRight=false;
                sbString=sbString+"第"+(i+1)+"行获取的正确答案错误！</br>";
            }
            questionDOList.add(questionDO);
        }
        //设置试卷拥有的试题数量
        libraryDO.setQuestionNum(sheet.getPhysicalNumberOfRows()-1);
        if(!isRight){
            throw new ApiException(file.getName()+"  出错了 :"+sbString);
        }
        map.put(APIConstants.QUESTION_LIST, questionDOList);
        map.put(APIConstants.ANSWER_LIST, answerDOList);

        return map;
    }

}
